/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.projecao.spe.servlets;

import br.projecao.spe.modelo.Usuario;
import java.io.IOException;
import javax.persistence.Query;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Desenvolvimento
 */
public class LoginServlet extends HttpServlet {

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("spePU");
        EntityManager em = emf.createEntityManager();
        String pagina = "/index.jsp";
        //Preeche o objeto com os dados da tela
        Usuario usuario = preecheUsuario(request);
        //Validar o login
        Query query = em.createNamedQuery("Usuario.findByLogin");
        query.setParameter("login", usuario.getLogin());
        Usuario usuarioBanco = null;

        try {
            usuarioBanco = (Usuario) query.getSingleResult();
        } catch (NoResultException e) {
            request.setAttribute("MSG", "Usuário não cadastrado!");
            getServletContext().getRequestDispatcher(pagina).forward(request, response);
            return;
        }
        if (usuario.getSenha().equals(usuarioBanco.getSenha())) {
            //Login ok
            request.getSession().setAttribute("USUARIO", usuarioBanco);
            pagina = "/menu.jsp";
        } else {
            //Senha incorreta
            request.setAttribute("MSG", "Senha incorreta!");
        }
        //Redirecionar para a página escolhida
        getServletContext().getRequestDispatcher(pagina).forward(request, response);

    }

    private Usuario preecheUsuario(HttpServletRequest request) {
        Usuario usuario = new Usuario();
        usuario.setLogin(request.getParameter("LOGIN"));
        usuario.setSenha(request.getParameter("SENHA"));
        return usuario;
    }
}
